package org.urchr.beorganized.dao;

import com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class XMLDocumentBuilder {
    
    private Element rootElement = null;
    private Document doc = null;
    
    /** Creates a new instance of XMLDocumentBuilder */
    public XMLDocumentBuilder() {
    }
    
    public static String nodeToString(Node node){
        XMLDocumentBuilder xml = new XMLDocumentBuilder();
        return xml.makeXML(node);
    }
    
    public void addText(Element node, String text){
        node.appendChild(getDocument().createTextNode(text));
    }
    
	public void addChildWithValue(Node e, String name, String err){
		Element n = doc.createElement(name);
		e.appendChild(n);
		addText(n, err==null?"":err);
	}
	
    public Document getDocument(){
        if(doc==null){
            try {
                DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                dbfac.setNamespaceAware(true);
                DocumentBuilder docBuilder;
                
                docBuilder = dbfac.newDocumentBuilder();
                doc = docBuilder.newDocument();

            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            }            
        }
        return doc;
    }
    
    public boolean loadXML(String source){
        try {
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder;

            docBuilder = dbfac.newDocumentBuilder();
            doc = docBuilder.parse(new InputSource(new StringReader(source)));
            rootElement = doc.getDocumentElement();
            return true;
        } catch (SAXException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
//            ex.printStackTrace();
        }
        return false;
    }
    
    public boolean readXML(String fileName){
        try {
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder;

            docBuilder = dbfac.newDocumentBuilder();
            doc = docBuilder.parse(new FileInputStream(fileName));
            rootElement = doc.getDocumentElement();
            return true;
        } catch (SAXException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
//            ex.printStackTrace();
        }
        return false;
    }
    
    public boolean readXML(InputStream stream){
    	return readXML(stream, false); 
    }
    
    public boolean readXML(InputStream stream, boolean ns){
        try {
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            dbfac.setNamespaceAware(ns);
            
            DocumentBuilder docBuilder;
            docBuilder = dbfac.newDocumentBuilder();
            
            doc = docBuilder.parse(stream);
            rootElement = doc.getDocumentElement();
            return true;
        } catch (SAXException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
//            ex.printStackTrace();
        }
        return false;
    }
    
    public Element getRootElement(){
    	return getRootElement("root");
    }
    
    public Element getRootElement(String name){
        if(rootElement==null){
            rootElement = getDocument().createElement(name);
            getDocument().appendChild(rootElement);
        }
        return rootElement;
    }
    
    public Element createElement(String name){
        return createElement(name, null);
    }
    
    public Element createElement(String name, String ns){
    	String _name = name;
    	String _prefix = "";
    	int idx = _name.indexOf(":");
    	if(idx!=-1){
    		_prefix = _name.substring(0, idx);
    		_name = _name.substring(idx+1);
    	}
    	if(ns!=null && !"".equals(ns)){
    		Element e = getDocument().createElementNS(ns, _name);
    		e.setPrefix(_prefix);
    		return e;
    	}
        return getDocument().createElement(_name);
    }
    
    public String makeXML(){
        return makeXML(getDocument());
        
    }

    public static String makeXML(Node root){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(root);
            trans.transform(source, result);
            String xmlString = sw.toString();
            return xmlString;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return "";
    }
    
    public static boolean writeXML(Node root, Writer writer){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "no");

            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(root);
            trans.transform(source, result);
            return true;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return false;
    }
    
    public static boolean writeXML(XMLReader reader, Writer writer, boolean header){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, header?"no":"yes");
            trans.setOutputProperty(OutputKeys.INDENT, "no");

            StreamResult result = new StreamResult(writer);
            SAXSource source = new SAXSource(reader, null);
            trans.transform(source, result);
            return true;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return false;    	
    }
    
    public static boolean writeXML(Node root, OutputStream stream){
    	return writeXML(root, stream, true);
    }
    
    public static boolean writeXML(XMLReader reader, OutputStream stream, boolean header){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, header?"no":"yes");
            trans.setOutputProperty(OutputKeys.INDENT, "no");

            StreamResult result = new StreamResult(stream);
            SAXSource source = new SAXSource(reader, null);
            trans.transform(source, result);
            return true;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return false;    	
    }
    
    public static boolean writeXML(Node root, OutputStream stream, boolean header){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, header?"no":"yes");
            trans.setOutputProperty(OutputKeys.INDENT, "no");

            StreamResult result = new StreamResult(stream);
            DOMSource source = new DOMSource(root);
            trans.transform(source, result);
            return true;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return false;
    }
    
    public static boolean writeXML(Node root, String fileName){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            FileOutputStream fos = new FileOutputStream(fileName);
            StreamResult result = new StreamResult(fos);
            DOMSource source = new DOMSource(root);
            trans.transform(source, result);
            fos.close();
            return true;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return false;
    }
    
    public DTMNodeList evaluateXPath(String expression){
        return evaluateXPath(expression, getDocument());
    }
    
    public DTMNodeList evaluateXPath(String expression, Node e){
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            return (DTMNodeList) xpath.evaluate(expression, e, XPathConstants.NODESET);
        } catch (XPathExpressionException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public Node evaluateXPathOneNode(String expression){
        return evaluateXPathOneNode(expression, getDocument());
    }
    
    public Node evaluateXPathOneNode(String expression, Node e){
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            return (Node) xpath.evaluate(expression, e, XPathConstants.NODE);
        } catch (XPathExpressionException ex) {
//            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public String makeXSLTransform(String xslPath){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Templates template = 
                    transfac.newTemplates(new StreamSource(this.getClass().getResourceAsStream(xslPath)));
            Transformer trans = template.newTransformer();
            
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(getDocument());
            trans.transform(source, result);
            String xmlString = sw.toString();
            
            return xmlString;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return "";        
    }
}
